package com.qd.tc.service;

import com.qd.util.ReflectUtils;
import org.dom4j.Element;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 * User: haowenchao
 * Date: 14-10-15
 * Time: 上午10:58
 * To change this template use File | Settings | File Templates.
 */
public class AbstractTCDataConvertService {

    /**
     * 解析XMLDocElement列表为java对象
     * @param elementList XMLDocElement列表
     * @param obj java对象
     */
    protected void reflectResultToObj(List<Element> elementList, Object obj){
        reflectResultToObj(elementList, obj, null);
    }

    /**
     * 解析XMLDocElement列表为java对象
     * @param elementList XMLDocElement列表
     * @param obj java对象
     * @param excludeFields 忽略解析的字段
     */
    protected void reflectResultToObj(List<Element> elementList, Object obj, Set<String> excludeFields){
        for(Element element : elementList){
            String fieldName = element.getName();//实体类属性值
            if(ReflectUtils.hasField(fieldName, obj) && (excludeFields ==null || !excludeFields.contains(fieldName))){
                ReflectUtils.setFieldValue(obj, fieldName, element.getStringValue());
            }
        }
    }

    /**
     * 解析XMLDocElement列表为map对象
     * @param elementList XMLDocElement列表
     * @param map map对象
     */
    protected void reflectResultToMap(List<Element> elementList, Map<String, String> map){
        reflectResultToMap(elementList, map, null);
    }

    /**
     * 解析XMLDocElement列表为map对象
     * @param elementList XMLDocElement列表
     * @param map map对象
     * @param excludeFields 忽略解析的字段
     */
    protected void reflectResultToMap(List<Element> elementList, Map<String, String> map, Set<String> excludeFields){
        Set<String> keySet = map.keySet();
        for(Element element : elementList){
            String fieldName = element.getName();//实体类属性值
            if(keySet.contains(fieldName) && (excludeFields ==null || !excludeFields.contains(fieldName))){
                map.put(fieldName, element.getStringValue());
            }
        }
    }
}
